<template>
  <div class="editor-box">
  <div>
    <FOOTER @send_user_text="sender_user_text"/>
  </div>
  <div class="editor-container">
   
    <div style="position: sticky; top:0px;">
      <div class="editor-toolbar editor-btn-group" role="group">
        <button v-for="btn in toolbarButtons" :key="btn.command" @click="execCmd(btn.command)" class="editor-btn" :title="btn.title">
          <span :class="btn.icon"></span>
        </button>
        
        <div class="editor-color-picker">
          <input type="color" ref="foreColorInput" @input="applyColor('foreColor')" title="文本颜色" />
          <span>文本颜色</span>
        </div>
       
        <div class="editor-color-picker">
          <input type="color" ref="hiliteColorInput" @input="applyColor('hiliteColor')" title="高亮颜色" />
          <span>高亮颜色</span>
        </div>
       
        <button @click="insertImage" class="editor-btn" title="插入图片">
          <Icon type="ios-image-outline" style="font-size: 20px;" />
        </button>
      </div>
    </div>
    
    <input type="text" placeholder="请输入标题" ref="titleInput" maxlength="50" class="editor-title" v-model="title" />
    
    <div id="editor" contenteditable="true" ref="editor" @keydown="handleTab">
      <p>请在此处进行编辑，目前支持选中处理，标题正在更新中！</p>
      <p>尝试选中一些文本并选择工具栏调整！</p>
    </div>

    <TEXTINFO ref="get_textinfo"/>
  </div>
  </div>
</template>

<script setup>
import { ref, inject,reactive } from "vue";
import TEXTINFO from "./textinfo.vue";
import FOOTER from "./footer.vue";
import { update_user_text } from "@/api/community/main.js";
import { warning } from '@/static/js/alert';
import { fileToBase64 } from "@/static/js/files/lifedata.js";

const user_store = inject('user')();
const foreColorInput = ref(null);
const hiliteColorInput = ref(null);
const editor = ref(null);
const title = ref('');
const titleInput = ref(null);
const get_textinfo = ref(null);
const image_box = ref([]);
const timer=reactive({
  
})
const toolbarButtons = [
  { command: "bold", title: "加粗", icon: "iconfont icon-jiacu" },
  { command: "italic", title: "斜体", icon: "iconfont icon-xieti" },
  { command: "underline", title: "下划线", icon: "iconfont icon-xiahuaxian" },
  { command: "strikeThrough", title: "删除线", icon: "iconfont icon-shanchuxian" },
  { command: "justifyLeft", title: "左对齐", icon: "iconfont icon-zuoduiqi" },
  { command: "justifyCenter", title: "居中对齐", icon: "iconfont icon-juzhongduiqi" },
  { command: "justifyRight", title: "右对齐", icon: "iconfont icon-youduiqi" },
  { command: "justifyFull", title: "两端对齐", icon: "iconfont icon-liangduanduiqi" },
  { command: "insertUnorderedList", title: "无序列表", icon: "iconfont icon-unorderedList" },
  { command: "insertOrderedList", title: "有序列表", icon: "iconfont icon-youxuliebiao" },
  { command: "outdent", title: "减少缩进", icon: "iconfont icon-22jianshaosuojin" },
  { command: "indent", title: "增加缩进", icon: "iconfont icon-zengjiasuojinliang" },
  { command: "undo", title: "撤销", icon: "iconfont icon-fanhui" }
];

const execCmd = (command, value = null) => {
  document.execCommand(command, false, value);
  editor.value.focus();
};

const applyColor = (command) => {
  const input = command === 'foreColor' ? foreColorInput.value : hiliteColorInput.value;
  if (input && input.value) {
    const color = input.value;
    const styleProperty = command === 'foreColor' ? 'color' : 'backgroundColor';
    const selection = window.getSelection();

    if (selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);

      if (!range.collapsed) {
        document.execCommand(command, false, color); // 使用 execCommand 设置颜色
      } else {
        // 如果没有选中文字，只设置光标处的样式
        const span = document.createElement('span');
        span.style[styleProperty] = color;
        span.textContent = '\u200B'; // 零宽空格避免换行
        range.insertNode(span);

        // 移动光标到插入的零宽空格之后
        range.setStartAfter(span);
        range.setEndAfter(span);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    }
  }
};
const handleTab = (event) => {
  if (event.key === "Tab") {
    event.preventDefault();
    document.execCommand("insertText", false, "    ");
  }
};

const insertImage = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.onchange = async (event) => {
    const file = event.target.files[0];
    if (file) {
      try {
        const base64 = await fileToBase64(file);
        image_box.value.push(base64);

        const img = document.createElement('img');
        img.src = base64;
        img.style.maxWidth = '100%';
        img.style.height = 'auto';
        img.style.cursor = 'pointer';
        img.style.border = '1px dashed #ccc';

        const selection = window.getSelection();
        if (selection.rangeCount > 0) {
          const range = selection.getRangeAt(0);
          if (editor.value.contains(range.commonAncestorContainer)) { // 确保图片插入在编辑器内
            range.insertNode(img);

            range.setStartAfter(img);
            range.setEndAfter(img);
            selection.removeAllRanges();
            selection.addRange(range);
          } else {
            warning('请将光标置于编辑器内再插入图片');
          }
        }
      } catch (error) {
        console.error('Error inserting image:', error);
        warning('图片插入失败');
      }
    }
  };
  input.click();
};

const truth_sender_user_text = async () => {
  async () => {
    const skecth = get_textinfo.value?.getSkecth();
    const tips = get_textinfo.value?.getSelectedTips();
    const article_type = get_textinfo.value?.getArticleTypes();
    const article_kind = get_textinfo.value?.getArticleCategory();
    const visibility = get_textinfo.value?.getVisibility();

    if (!article_type || !title.value) {
      warning("请完善信息");
      return;
    }

    const dataform = new FormData();

    image_box.value.forEach((img, index) => {
      dataform.append(`file${index}`, img);
    });

    dataform.append('sketch', skecth);
    dataform.append('kind', article_kind);
    dataform.append('title', title.value);
    dataform.append('text', editor.value.innerHTML);
    dataform.append('author', user_store.value.get_user().id);
    dataform.append("username", user_store.value.get_user().username);
    dataform.append('resource', article_type);
    dataform.append('tips', tips);
    dataform.append('visibility', visibility);

    const indeximage = get_textinfo.value?.getCoverFile();
    if (indeximage) {
      try {
        const index_image = await fileToBase64(indeximage);
        dataform.append('index_image', index_image);
      } catch (error) {
        console.error('Error processing cover image:', error);
        warning('封面图片处理失败');
        return;
      }
    } else {
      dataform.append('index_image', null);
    }

    try {
      await update_user_text(dataform);

      title.value = '';
      editor.value.innerHTML = '<p>请在此处进行编辑，目前支持选中处理，标题正在更新中！</p><p>尝试选中一些文本并选择工具栏调整！</p>';
      image_box.value = [];
    } catch (error) {
      console.error('Error submitting article:', error);
      warning('提交失败，请重试');
    }
  }
}
const sender_user_text = () => { 
  if (timer['sender_user_text']) { 
    clearTimeout(timer['sender_user_text']);
  }
  timer['sender_user_text'] = setTimeout(() => {
      truth_sender_user_text();
  }, 2000);
}

</script>

<style scoped>
.editor-box{
  display: flex;
  overflow: hidden;
  height: 100vh;
}
.editor-container {
  max-width: max-content;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-direction: column;
  gap: 15px;
  overflow: scroll;
}
.editor-container::-webkit-scrollbar {
  width: 8px;
}

.editor-toolbar {
  border: 1px solid #e0e0e0;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
  display: flex;
  flex-wrap: nowrap;
  gap: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

.editor-btn,
.editor-color-picker {
  margin: 0;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  background-color: #ffffff;
  color: #333;
  cursor: pointer;
  transition: background-color 0.2s, box-shadow 0.2s;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
  flex-shrink: 0;
}

.editor-btn:hover,
.editor-color-picker:hover {
  background-color: #f0f0f0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.editor-btn:active,
.editor-color-picker:active {
  background-color: #e0e0e0;
}

.editor-color-picker input[type="color"] {
  width: 24px;
  height: 24px;
  padding: 0;
  border: none;
  cursor: pointer;
  background: none;
}

#editor {
  border: 1px solid #e0e0e0;
  min-height: 500px;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  font-family: 'Arial', sans-serif;
  font-size: 16px;
  line-height: 1.6;
  color: #333;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  outline: none;
}

.editor-title {
  font-size: 18px;
  line-height: 18px;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  padding: 10px;
  outline: none;
  width: 100%;
}
</style>